import { MAX_NAME_LENGTH } from '@/common';
import Modals from '@/components/modals/Modals';
import ModalsFooterBtn from '@/components/modals/ModalsFooterBtn';
import { ApiItem, Property } from '@/types/api';
import { MinusCircleOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, Modal, Select, Space, Row, Col, App } from 'antd';
import { FormInstance } from 'antd/es/form';
import { useEffect, useState } from 'react';
import TagInput from '@/components/inputs/TagInput';
const { TextArea } = Input;
interface Props {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (item: ApiItem) => void;
  onCancelText?: string; // 可选参数
  onConfirmText?: string; // 可选参数
}

interface Parameter {
  name: string;
  type: string;
  require: boolean;
  description: string;
  enum: string[];
}

interface FormValues {
  http_url: string;
  http_method: string;
  name: string;
  description: string;
  parameters: Parameter[];
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};

export const validateAndConvertValue = (
  type: string,
  value: string,
): { isValid: boolean; convertedValue: any } => {
  try {
    switch (type) {
      case 'string':
        return { isValid: true, convertedValue: value };
      case 'integer':
        const intValue = parseInt(value);
        const isValid = !isNaN(intValue) && /^-?\d+$/.test(value);
        return { isValid, convertedValue: isValid ? intValue : value };
      case 'number':
        const numValue = parseFloat(value);
        const isValidNumber = !isNaN(numValue) && /^-?\d*\.?\d+$/.test(value);
        return { isValid: isValidNumber, convertedValue: isValidNumber ? numValue : value };
      case 'boolean':
        const boolValue = value.toLowerCase();
        if (boolValue === 'true' || boolValue === 'false') {
          return { isValid: true, convertedValue: boolValue === 'true' };
        }
        return { isValid: false, convertedValue: null };
      case 'array':
        return { isValid: false, convertedValue: null };
      case 'object':
        return { isValid: false, convertedValue: null };
      default:
        return { isValid: false, convertedValue: null };
    }
  } catch {
    return { isValid: false, convertedValue: null };
  }
};

const NewApiModal = ({ visible, onCancel, onConfirm }: Props) => {
  const [form] = Form.useForm<FormValues>();
  const { message } = App.useApp();
  const cvToDic = (parameters: Parameter[]): Record<string, Property> => {
    return parameters.reduce((acc, param) => {
      const property: Property = {
        type: param.type,
        description: param.description,
      };

      // 只有当 enum 不为空列表时才添加 enum 字段
      if (param.enum && param.enum.length > 0) {
        property.enum = param.enum;
      }

      acc[param.name] = property;
      return acc;
    }, {} as Record<string, Property>);
  };

  const onFinish = async (values: FormValues) => {
    console.log(123123);

    const res = await form.validateFields();
    if (!res.name) {
      message.error('请输入名称');
      return;
    }
    if (res.name.length > MAX_NAME_LENGTH) {
      message.error(`数据接口名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!res) {
      message.warning('请填写完整数据接口信息！');
      return;
    }

    // 验证 enum 参数的合法性
    if (values.parameters) {
      for (const param of values.parameters) {
        if (param.enum && param.enum.length > 0) {
          if (param.type === 'array' || param.type === 'object') {
            message.warning(`参数 "${param.name}" 为 ${param.type} 类型，不支持示例值配置`);
            return;
          }

          const invalidValues = param.enum.filter((value) => {
            const { isValid } = validateAndConvertValue(param.type, String(value));
            return !isValid;
          });

          if (invalidValues.length > 0) {
            message.warning(`参数 "${param.name}" 的示例值包含无效的 ${param.type} 类型值`);
            return;
          }

          // 转换所有值为正确的类型
          param.enum = [
            ...new Set(
              param.enum.map((value) => {
                const { convertedValue } = validateAndConvertValue(param.type, String(value));
                return convertedValue;
              }),
            ),
          ];
        }
      }
    }

    const item: ApiItem = {
      http_url: values.http_url,
      http_method: values.http_method,
      type: 'function',
      function: {
        name: values.name,
        description: values.description,
        parameters: {
          type: 'object',
          properties: values.parameters ? cvToDic(values.parameters) : {},
          required: values.parameters
            ? values.parameters.filter((item) => item.require).map((item) => item.name)
            : [],
        },
      },
    };
    onConfirm && onConfirm(item);
  };

  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [visible]);

  return (
    <Modals
      title={<div>新建数据接口</div>}
      open={visible}
      onCancel={onCancel}
      okText="确定"
      cancelText="取消"
      width={700}
      maskClosable={false}
      footerCancelHidden={true}
      footerOkHidden={true}
      footer={false}
    >
      <div className=" mt-5 h-full w-full">
        {/* <Form form={form} onFinish={onFinish}>
         
        </Form> */}
        <Form
          form={form}
          name="basic"
          {...formItemLayout}
          initialValues={{ remember: true }}
          autoComplete="on"
          onFinish={onFinish}
        >
          <Form.Item
            label="数据接口名称"
            name="name"
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: '请输入数据接口名称!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="数据接口地址"
            name="http_url"
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: '请输入数据接口地址!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="数据接口说明"
            name="description"
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: '请输入数据接口说明!' }]}
          >
            <TextArea />
          </Form.Item>

          <Form.Item
            name="http_method"
            label="HTTP method"
            wrapperCol={{ span: 16 }}
            rules={[{ required: true, message: '请选择HTTP method!' }]}
          >
            <Select>
              <Select.Option value="get">get</Select.Option>
              <Select.Option value="post">post</Select.Option>
              <Select.Option value="put">put</Select.Option>
              <Select.Option value="delete">delete</Select.Option>
            </Select>
          </Form.Item>

          <Form.List name="parameters">
            {(fields, { add, remove }, { errors }) => (
              <>
                {fields.map((field, index) => (
                  <Form.Item
                    {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                    label={index === 0 ? '参数' : ''}
                    required={false}
                    key={`fields_${field.key}`}
                  >
                    <Row gutter={[16, 16]} style={{ width: '100%' }}>
                      <Col span={20}>
                        <Row gutter={[16, 16]}>
                          <Col span={8}>
                            <Form.Item
                              name={[field.name, 'name']}
                              rules={[{ required: true, message: '请输入参数名' }]}
                            >
                              <Input placeholder="参数名" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              name={[field.name, 'description']}
                              rules={[{ required: true, message: '请输入参数说明' }]}
                            >
                              <Input placeholder="参数说明" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              name={[field.name, 'type']}
                              rules={[{ required: true, message: '请选择参数类型' }]}
                            >
                              <Select placeholder="参数类型">
                                <Select.Option value="string">string</Select.Option>
                                <Select.Option value="integer">integer</Select.Option>
                                <Select.Option value="boolean">boolean</Select.Option>
                                <Select.Option value="number">number</Select.Option>
                                <Select.Option value="array">array</Select.Option>
                                <Select.Option value="object">object</Select.Option>
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row>
                          <Col span={24}>
                            <Form.Item
                              name={[field.name, 'enum']}
                              rules={[{ required: false, message: '请输入示例值' }]}
                            >
                              <TagInput
                                className=""
                                placeholder="输入示例值，并按回车"
                                minRows={1}
                                warningMessage="示例值已存在"
                                onChange={(tags) => {
                                  const formValues = form.getFieldsValue();
                                  const parameters = formValues.parameters || [];
                                  const currentType = parameters[field.name].type;

                                  if (
                                    (currentType === 'array' || currentType === 'object') &&
                                    tags.length > 0
                                  ) {
                                    message.warning('array 和 object 类型不支持示例值配置');
                                    return;
                                  }

                                  const validTags: any[] = [];
                                  let hasInvalidValue = false;

                                  tags.forEach((tag) => {
                                    const { isValid, convertedValue } = validateAndConvertValue(
                                      currentType,
                                      String(tag),
                                    );
                                    if (isValid) {
                                      validTags.push(convertedValue);
                                    } else {
                                      hasInvalidValue = true;
                                    }
                                  });

                                  if (hasInvalidValue) {
                                    message.warning(`请输入有效的 ${currentType} 类型值`);
                                    return;
                                  }

                                  parameters[field.name].enum = validTags;
                                  form.setFieldsValue({ parameters });
                                }}
                              />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Col>
                      <Col span={4}>
                        <div style={{ display: 'flex', alignItems: 'center', height: '32px' }}>
                          <Form.Item
                            valuePropName="checked"
                            name={[field.name, 'require']}
                            style={{ marginBottom: 0 }}
                          >
                            <Checkbox>
                              <span className="text-nowrap">必需</span>
                            </Checkbox>
                          </Form.Item>
                          <MinusOutlined
                            onClick={() => remove(index)}
                            style={{ marginLeft: '8px' }}
                          />
                        </div>
                      </Col>
                    </Row>
                  </Form.Item>
                ))}
                <Form.Item {...formItemLayoutWithOutLabel}>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add({
                        name: '',
                        type: 'string',
                        require: true,
                      });
                    }}
                    style={{ width: '60%' }}
                    icon={<PlusOutlined />}
                  >
                    添加参数
                  </Button>
                  <Form.ErrorList errors={errors} />
                </Form.Item>
              </>
            )}
          </Form.List>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space size={56}>
              <ModalsFooterBtn
                onClick={() => {
                  form.resetFields();
                  onCancel();
                }}
              >
                取消
              </ModalsFooterBtn>
              <ModalsFooterBtn htmlType="submit" type="primary">
                确定
              </ModalsFooterBtn>
              {/* <Button
                shape="round"
                className={
                  `!h-auto !w-auto !px-6 !py-2 !text-sm !leading-none`
                }
                onClick={() => {
                  form.resetFields();
                  onCancel();
                }}
              >
                取消
              </Button> */}
              {/* <Button
                type="primary"
                shape="round"
                className={
                  `!h-auto !w-auto !px-6 !py-2 !text-sm !leading-none `
                }
                htmlType="submit">
                确定
              </Button> */}
            </Space>
          </Form.Item>
        </Form>
        {/* <Input allowClear placeholder="请输入同步地址" /> */}
      </div>
    </Modals>
  );
};

export default NewApiModal;
